package com.xinghou.platform.dao.mange.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.xinghou.platform.dao.bases.JdbcTemplate;
import com.xinghou.platform.dao.bases.database.CustomerContextHolder;
import com.xinghou.platform.dao.mange.VestDAO;
import com.xinghou.platform.model.main.Vest;

/**
 * 
 * @author wlw
 * 
 */
@Repository
public class VestDAOImpl implements VestDAO {
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	public int getVest(String vestName, String vestPass)throws DataAccessException {
		
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_READ);
		String sql="SELECT count(*) FROM vest WHERE vest_name=? AND vest_pass=?";
		int ret = jdbcTemplate.queryForInt(sql, new Object[] {vestName,vestPass});
		CustomerContextHolder.clearCustomerType();
		return ret;	
	}
	
	public int getVestId(String vestName) throws DataAccessException {
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_READ);
		String sql="SELECT 	vest_id FROM vest v WHERE v.vest_name=? ";
		int vestId = jdbcTemplate.queryForObject(sql, new Object[] {vestName},new intMapper());
		CustomerContextHolder.clearCustomerType();
		return vestId;	
	}

	private static final class intMapper implements RowMapper<Integer> {
		public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
			return rs.getInt(1);
		}
	}
	
	private static final class VestMapper implements RowMapper<Vest> {
		public Vest mapRow(ResultSet rs, int rowNum) throws SQLException {
			Vest vest = new Vest();
			vest.setVestId(rs.getInt("vest_id"));
			vest.setVestName(rs.getString("vest_name"));
			vest.setVestPass(rs.getString("vest_pass"));
			vest.setVestStatus(rs.getInt("vest_status"));
			return vest;
		}
	}

	@Override
	public List<Vest> getAllVests() throws DataAccessException {
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_READ);
		String sql="SELECT * FROM vest";
		List<Vest> list = jdbcTemplate.query(sql, new Object[] {}, new VestMapper());
		CustomerContextHolder.clearCustomerType();
		return list;	
	}
}
